package realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.*;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import realtime.bean.BackUserCountBean;
import realtime.util.ClickHouseUtil;
import realtime.util.DateFormatUtil;
import realtime.util.MyKafkaUtil;

import java.time.Duration;

public class Dws_User_BackUser {
    public static void main(String[] args) throws Exception {
        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(10000L);
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/flinkcdc/220926");

        //设置HDFS用户信息
        //System.setProperty("HADOOP_USER_NAME", "atguigu");


        //TODO 2.读取Kafka DWD层 页面日志主题数据创建流
        String topic = "dwd_traffic_page_log";
        String groupId = "use_backUser_edu";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));

        //TODO 3.转换为JSON对象并过滤
        //统计的指标与用户有关，uid不为null的数据才是有用的
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject jsonObject = JSON.parseObject(value);
                String uid = jsonObject.getJSONObject("common").getString("uid");
                String lastPageId = jsonObject.getJSONObject("page").getString("last_page_id");

                if (uid != null && (lastPageId == null || lastPageId.equals("login"))) {
                    out.collect(jsonObject);
                }
            }
        });

        //TODO 4.提取时间戳生成Watermark
        SingleOutputStreamOperator<JSONObject> jsonObjWithWMDS = jsonObjDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return element.getLong("ts");
            }
        }));

        //TODO 5.按照uid分组
        KeyedStream<JSONObject, String> keyedStream = jsonObjWithWMDS.keyBy(value -> value.getJSONObject("common").getString("uid"));

        //TODO 6.去重并转换为JavaBean对象
        SingleOutputStreamOperator<BackUserCountBean> javaBeanDS = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, BackUserCountBean>() {

            private ValueState<String> lastVistDt;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("last-state", String.class);
                //状态初始化
                lastVistDt = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public void flatMap(JSONObject value, Collector<BackUserCountBean> out) throws Exception {
                //获取状态数据以及当前数据中的日期
                String lastDt = lastVistDt.value();
                Long ts = value.getLong("ts");
                String curDt = DateFormatUtil.toDate(ts);

                Long buCt = 0L;
                Long nuCt = 0L;
                Long nuOftenCt = 1L;

                if (lastDt == null) {
                    nuCt = 1L;
                    lastVistDt.update(curDt);
                } else if (!lastVistDt.equals(curDt)) {


                    if (((ts - DateFormatUtil.toTs(lastDt)) / 24 * 3600 * 1000L) > 7) {
                        buCt = 1L;
                    }
                }

                out.collect(new BackUserCountBean("", "", buCt, nuCt, nuOftenCt, null));
            }
        });

        //TODO 7.开窗、聚合
        SingleOutputStreamOperator<BackUserCountBean> resultDS = javaBeanDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<BackUserCountBean>() {
                    @Override
                    public BackUserCountBean reduce(BackUserCountBean value1, BackUserCountBean value2) throws Exception {
                        value1.setBuCt(value1.getBuCt() + value2.getBuCt());
                        value1.setNuCt(value1.getNuCt() + value2.getNuCt());
                        value1.setNuOfenCt(value1.getNuOfenCt() + value2.getNuOfenCt());
                        return value1;
                    }
                }, new AllWindowFunction<BackUserCountBean, BackUserCountBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<BackUserCountBean> values, Collector<BackUserCountBean> out) throws Exception {
                        BackUserCountBean next = values.iterator().next();

                        next.setTs(System.currentTimeMillis());
                        next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        next.setStt(DateFormatUtil.toYmdHms(window.getStart()));

                        //输出数据
                        out.collect(next);
                    }
                });

        //TODO 8.写出数据
//        resultDS.print("resultDS>>>>");
        resultDS.addSink(ClickHouseUtil.getSinkFunction("insert into dws_user_back_often_new_window values(?,?,?,?,?,?)"));

        //TODO 9.启动任务
        env.execute("Dws_User_BackUser");


    }
}
